package com.aloda.ojsandbox.sandbox.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.aloda.ojsandbox.anno.SandboxStrategyConfig;
import com.aloda.ojsandbox.exception.BaseException;
import com.aloda.ojsandbox.pojo.dto.ExecuteCodeRequest;
import com.aloda.ojsandbox.pojo.dto.ExecuteCodeResponse;
import com.aloda.ojsandbox.pojo.dto.ExecuteMessage;
import com.aloda.ojsandbox.pojo.entity.JudgeInfo;
import com.aloda.ojsandbox.pojo.enums.CodeSandboxLanguageEnum;
import com.aloda.ojsandbox.pojo.enums.ResponseEnum;
import com.aloda.ojsandbox.properties.CodeSandboxProperties;
import com.aloda.ojsandbox.sandbox.CodeSandbox;
import com.aloda.ojsandbox.utils.ProcessUtils;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author aloda
 * @Date 2025/4/30 16:17
 */
@Slf4j
@SandboxStrategyConfig(sandboxLanguageType = CodeSandboxLanguageEnum.JAVA)
public class JavaDockerCodeSandbox implements CodeSandbox {

    @Resource
    private CodeSandboxProperties codeSandboxProperties;

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    private static final long MAX_TIME_LIMIT = 30000L;

    private static final Boolean FIRST_INIT = true;

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        // 获取参数
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        Long time = executeCodeRequest.getTime();
        Long memory = executeCodeRequest.getMemory();

        // 1. 把用户的代码保存为文件
        File userCodeFile = null;
        try {
            userCodeFile = saveCodeToFile(code);
        } catch (Exception e) {
            throw new BaseException(ResponseEnum.FILE_SAVE_ERROR);
        }

        // 2. 编译代码，得到 class 文件
        try {
            ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
            if (compileFileExecuteMessage.getExitValue() != 0) {
                throw new BaseException(ResponseEnum.COMPILE_FILE_ERROR.getStatus(), compileFileExecuteMessage.getErrorMessage());
            }
        } catch (Exception e) {
            // 5. 文件清理
            boolean b = deleteFile(userCodeFile);
            if (!b) {
                log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
            }
            throw new BaseException(ResponseEnum.COMPILE_FILE_FAILURE);
        }

        // 3. 执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);

        // 4. 收集整理输出结果
        ExecuteCodeResponse outputResponse = null;
        try {
            outputResponse = getOutputResponse(executeMessageList);
        } catch (Exception e) {
            throw new BaseException(ResponseEnum.RESULT_GET_ERROR);
        }

        // 5. 文件清理
        boolean b = deleteFile(userCodeFile);
        if (!b) {
            log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
        }
        return outputResponse;
    }

    /**
     * 1. 把用户的代码保存为文件
     * @param code 用户代码
     * @return
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        return FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
    }

    /**
     * 2、编译代码
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            return ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
        } catch (Exception e) {
            // return getErrorResponse(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 3、创建容器，把文件复制到容器内，运行代码文件得到结果
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        // 获取默认的 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String containerId = null;
        try {
            // 拉取镜像
            String image = codeSandboxProperties.getDockerJavaImage();
            if (FIRST_INIT) {
                PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
                PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                    @Override
                    public void onNext(PullResponseItem item) {
                        System.out.println("下载镜像：" + item.getStatus());
                        super.onNext(item);
                    }
                };
                try {
                    pullImageCmd
                            .exec(pullImageResultCallback)
                            .awaitCompletion();
                } catch (InterruptedException e) {
                    System.out.println("拉取镜像异常");
                    throw new RuntimeException(e);
                }
            }

            System.out.println("下载完成");

            // 创建容器
            CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
            HostConfig hostConfig = new HostConfig();
            hostConfig.withMemory(100 * 1000 * 1000L);
            hostConfig.withMemorySwap(0L);
            hostConfig.withCpuCount(1L);
//        hostConfig.withSecurityOpts(Arrays.asList("seccomp={\\\"defaultAction\\\": \\\"SCMP_ACT_ALLOW\\\", \\\"syscalls\\\": [{\\\"name\\\": \\\"write\\\", \\\"action\\\": \\\"SCMP_ACT_ALLOW\\\"}, {\\\"name\\\": \\\"read\\\", \\\"action\\\": \\\"SCMP_ACT_ALLOW\\\"}]}"));
            hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
            CreateContainerResponse createContainerResponse = containerCmd
                    .withHostConfig(hostConfig)
                    .withNetworkDisabled(true)
                    .withReadonlyRootfs(true)
                    .withAttachStdin(true)
                    .withAttachStderr(true)
                    .withAttachStdout(true)
                    .withTty(true)
                    .exec();
            System.out.println(createContainerResponse);
            containerId = createContainerResponse.getId();

            // 启动容器
            dockerClient.startContainerCmd(containerId).exec();

            // docker exec keen_blackwell java -cp /app Main 1 3
            // 执行命令并获取结果
            List<ExecuteMessage> executeMessageList = new ArrayList<>();
            long startTime = System.currentTimeMillis();
            for (String inputArgs : inputList) {
                StopWatch stopWatch = new StopWatch();
                String[] inputArgsArray = inputArgs.split(" ");
                String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
                ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                        .withCmd(cmdArray)
                        .withAttachStderr(true)
                        .withAttachStdin(true)
                        .withAttachStdout(true)
                        .exec();
                System.out.println("创建执行命令：" + execCreateCmdResponse);

                ExecuteMessage executeMessage = new ExecuteMessage();
                final String[] message = {null};
                final String[] errorMessage = {null};
                long time = 0L;
                // 判断是否超时
                final boolean[] timeout = {true};
                String execId = execCreateCmdResponse.getId();
                ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                    @Override
                    public void onComplete() {
                        // 如果执行完成，则表示没超时
                        timeout[0] = false;
                        super.onComplete();
                    }

                    @Override
                    public void onNext(Frame frame) {
                        // 计算当前执行时间
                        long currentTime = System.currentTimeMillis() - startTime;
                        if (currentTime > MAX_TIME_LIMIT) {
                            throw new BaseException("执行时间超出最大限制");
                        }
                        StreamType streamType = frame.getStreamType();
                        if (StreamType.STDERR.equals(streamType)) {
                            errorMessage[0] = new String(frame.getPayload());
                            System.out.println("输出错误结果：" + errorMessage[0]);
                        } else {
                            message[0] = new String(frame.getPayload());
                            System.out.println("输出结果：" + message[0]);
                        }
                        super.onNext(frame);
                    }
                };

                final long[] maxMemory = {0L};

                // 获取占用的内存
                StatsCmd statsCmd = dockerClient.statsCmd(containerId);
                ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {

                    @Override
                    public void onNext(Statistics statistics) {
                        System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                        maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                    }

                    @Override
                    public void close() throws IOException {

                    }

                    @Override
                    public void onStart(Closeable closeable) {

                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
                statsCmd.exec(statisticsResultCallback);
                try {
                    stopWatch.start();
                    dockerClient.execStartCmd(execId)
                            .exec(execStartResultCallback)
                            .awaitCompletion(TIME_OUT, TimeUnit.SECONDS);
                    stopWatch.stop();
                    time = stopWatch.getLastTaskTimeMillis();
                    statsCmd.close();
                } catch (InterruptedException e) {
                    System.out.println("程序执行异常");
                    throw new BaseException(ResponseEnum.CODE_RUN_ERROR);
                }
                executeMessage.setMessage(message[0]);
                executeMessage.setErrorMessage(errorMessage[0]);
                executeMessage.setTime(time);
                executeMessage.setMemory(maxMemory[0]);
                executeMessageList.add(executeMessage);
            }
            return executeMessageList;
        } finally {
            if (containerId != null) {
                try {
                    // 停止并删除容器
                    dockerClient.stopContainerCmd(containerId).exec();
                    dockerClient.removeContainerCmd(containerId).exec();
                    System.out.println("容器删除成功：" + containerId);
                } catch (Exception e) {
                    System.err.println("删除容器时出现异常：" + e.getMessage());
                }
            }
            // 关闭Docker客户端
            try {
                dockerClient.close();
            } catch (IOException e) {
                throw new BaseException(ResponseEnum.CODE_RUN_ERROR);
            }
        }
    }

    /**
     * 4、获取输出结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        JudgeInfo judgeInfo = new JudgeInfo();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        // 取内存最大值
        long maxMemory = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                judgeInfo.setMessage(errorMessage);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
            Long memory = executeMessage.getMemory();
            if (memory != null) {
                maxMemory = Math.max(maxMemory, memory);
            }
        }
        executeCodeResponse.setOutputList(outputList);
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        executeCodeResponse.setStatus(ResponseEnum.SUCCESS.getStatus());
        executeCodeResponse.setMessage(ResponseEnum.SUCCESS.getMessage());
        return executeCodeResponse;
    }

    /**
     * 5、删除文件
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }
}
